package kgc.crm.service.impl;

import kgc.crm.dto.BusinessListDto;
import kgc.crm.dto.LeadsListDto;
import kgc.crm.mapper.BusinessMapper;
import kgc.crm.mapper.BusinessProductMapper;
import kgc.crm.mapper.KgcCrmAdminFieldMapper;
import kgc.crm.model.Business;
import kgc.crm.model.BusinessProduct;
import kgc.crm.model.KgcCrmAdminField;
import kgc.crm.service.IBusinessService;
import kgc.crm.util.*;
import kgc.crm.vo.InsertBusinessVo;
import kgc.crm.vo.LeadsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.swing.*;
import java.io.BufferedReader;
import java.math.BigDecimal;
import java.util.Date;

@Service
@Slf4j
@Transactional
public class BusinessServiceImpl implements IBusinessService {
    @Autowired
    //商机
    private BusinessMapper businessMapper;
    //合同产品关系
    @Autowired
    private BusinessProductMapper productMapper;
    //自定义字段表
    @Autowired
    private KgcCrmAdminFieldMapper fieldMapper;
    /**
     *
     * @param vo 返回vo类型
     * @param apiToken  获取当前用户id
     * @return
     */
    @Override
    public ResponseEntity add(InsertBusinessVo vo, String apiToken) {
        if (EmptyChecker.isEmpty(vo)) {
            log.error("【商机模块】添加商机失败，vo对象不能为空");
            return ResultUtil.error("添加失败");
        }
        if (EmptyChecker.isEmpty(vo.getBusiness())) {
            log.error("【商机模块】添加商机失败，vo对象实体不能为空");
            return ResultUtil.error("添加失败");
        }
        //计算金额 判断金额是否相等 判断产品单价
        boolean productFlag = true;
        //总价格
        BigDecimal sumMoeny = new BigDecimal(0).setScale(2,BigDecimal.ROUND_HALF_UP);
        //用for循环遍历getBusinessProduct
        for (BusinessProduct item : vo.getBusinessProduct()) {
            //拿到每一个商品单价，这个类是用来存金额类型的  获取产品单价
            BigDecimal price = new BigDecimal(String.valueOf((item.getPrice())));
            //获取折扣  强转成BigDecimal类型  这边前端传的是1.0  百分之一就是 折扣/100
            BigDecimal discount = BigDecimal.valueOf(Arith.div(item.getDiscount(), new BigDecimal(100), 2));
            //计算打折的钱 = 单价 * 折扣
            BigDecimal mul = Arith.mul(price, discount);
            //计算出销售价格 = 单价 - 打折的钱
            BigDecimal sub = Arith.sub(price, mul);
            if (sub.doubleValue() != item.getSalesPrice().doubleValue()) {
                //如果计算出的销售价格 不等于 前台接受到的销售价格 则为false
                log.error("【商机模块】销售价格出错,对比失败,系统计算{},前段传递{}", sub, item.getSalesPrice());
                productFlag = false;
                break;
            }
            //计算出小计做对比
            //小计等于(折扣后价格等于销售价格*数量)
            BigDecimal total = Arith.mul(sub, new BigDecimal(item.getNum()));
            if (total.doubleValue() != item.getSubtotal().doubleValue()) {
                //如果系统计算出的小计不等于前端传递的话，就break；
                log.error("【商机模块】小计价格出错,对比失败，系统计算{},前段传递{}", total, item.getSubtotal());
                productFlag = false;
                break;
            }
            //总价格 = 循环每一次拿到的+ = 每一件商品的小计
            sumMoeny = Arith.add(sumMoeny, total);
        }
        //之所以不告诉为什么失败，是因为怕防止别人可以通过提示，来修改价格
        if (!productFlag) {
                return ResultUtil.error("添加失败");
            }
            //计算商机总价格
            //获取整单折扣
            BigDecimal discountRate =
                    BigDecimal.valueOf(Arith.div(vo.getBusiness().getDiscountRate(), new BigDecimal(100), 2));
            //计算整单折扣 打折的钱
            BigDecimal sumMul = Arith.mul(sumMoeny, discountRate);
            //计算出总金额 (=总价格-折扣价)
            BigDecimal subMoney = Arith.sub(sumMoeny, sumMul).setScale(2,BigDecimal.ROUND_HALF_UP);
            if (subMoney.doubleValue() != vo.getBusiness().getTotalPrice().doubleValue()) {
                log.error("【商机模块】总金额价格出错,对比失败，系统计算{},前段传递{}",subMoney,vo.getBusiness().getTotalPrice());
                return ResultUtil.error("添加失败");
            }
            //判断商机金额和总金额是否一致
            if (subMoney.doubleValue() != vo.getBusiness().getMoney().doubleValue()) {
                log.error("【商机模块】商机金额对比总金额失败，前端传递商机金额{},总金额{}",vo.getBusiness().getMoney(),subMoney);
                return ResultUtil.error("添加失败");
            }
        //这些业务都做完了，才准备开始添加
        //开始添加商机

        int i = -1;
        try {
            //添加属性
            Business business = vo.getBusiness();
            business.setOwnerUserId(JWTManager.getUserIDByToken(apiToken));
            business.setCreateUserId(business.getOwnerUserId());
            //创建时间 再数据库添加默认字段
            i = businessMapper.insert(vo.getBusiness());
        } catch (Exception e) {
            log.error("【商机模块】商机添加失败{}，sql语句执行出错，",e);
            //报错了就回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error("添加失败");
        }
        if (i <= 0) {
            log.error("【商机模块】添加失败");
            //报错了就回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error("商机添加失败");
        }
        //添加产品 批量添加
        //成功总计数
        int successCount = 0;
        for (BusinessProduct item : vo.getBusinessProduct()) {
            int insert = -1;
            try {
                //添加商机id
                item.setBusinessId(vo.getBusiness().getBusinessId());
                insert = productMapper.insert(item);
            } catch (Exception e) {
                log.error("【商机模块】产品添加失败{}，sql语句执行出错，",e);
                //报错了就回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultUtil.error("产品添加失败");
            }
            if (insert <= 0) {
                log.error("【商机模块】产品添加失败");
                //报错了就回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultUtil.error("产品添加失败");
            }
            successCount +=1;
        }
        if (successCount != vo.getBusinessProduct().size()) {
            //如果你添加产品总计数不等于list集合长度，代表没有完全添加成功
            log.error("【商机模块】添加失败，{}",vo.getBusinessProduct());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error("添加失败");
        }
        return ResultUtil.success("添加成功！");
    }

    @Override
    public ResponseEntity selectListById(LeadsVo vo, String apiToken) {
        String fieldName = "";
        //当前登录的用户ID
        Long businessId = JWTManager.getUserIDByToken(apiToken);
        if (!EmptyChecker.isEmpty(vo.getVo())) {
            KgcCrmAdminField field = fieldMapper.selectById(vo.getVo().getFieldId());
            String name = field.getFieldName();
        }
        BusinessListDto dto = new BusinessListDto(
                vo.getSearchVal(),(vo.getPageIndex()-1) * vo.getPageSize(),vo.getPageSize()
                ,vo.getVo(),fieldName
        );
        return ResultUtil.success(businessMapper.selectListByDto(dto));
    }
}

